define([
    'static/app/exampleDivisions',
    'static/app/menu',
    'static/app/date',
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/combotree",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "UtilDir/loading",    
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang",
], function (exampleDivisions, Menu, Date, Util, Tool, Combotree, SelectOrg, SearchBlock, Loading) {    
	$(document).ready(function (){
		var script   = document.createElement("script");
	    script.type  = "text/javascript";
	    script.src   = "/pcjd/static/app/detailview.js";
	    document.body.appendChild(script);
	})
    var getDivisionController = function () {
        return getServer() + "/platform/org/divisions/";
    };
    var getController = function () {
        return getServer() + "/pc";
    };
    var divisioncombotree // 行政区划组合树
    var menucombotree // 菜单组合树
    var selectedDivisions = [] // 组合树已选行政区划
    var selectedMenus = [] // 组合树已选的菜单

    // 初始化
    var init = function () {
        btnInit(); 
        createAuditGrid();
    }
 	// 表格輸入框
 	var obj = {}
 	//window.keyup = function(e) {
// 		console.log(e, $(e), $(e).val(), $(e).attr('data-divisionName'))
 		
 		//console.log(obj)
 		
 		//console.log(taskCode)
 	//}
 	window.checkNumberValue = function (inputObj) {
        //效验输入数字是否0-100        
        if(!/(^0$)|(^100$)|(^\d{1,2}$)/.test(inputObj.value)) {
            if(inputObj.value>100){
                inputObj.value = 100;
            }
            if(inputObj.value<0){
                inputObj.value = 0;
            }
        }
        var divisionCode = $(inputObj).attr('data-divisionCode')
 		var taskCode = $(inputObj).attr('data-taskCode')
 		var subkey = taskCode+"-"+divisionCode;
 		var value = $(inputObj).val()
		obj[subkey] = value
    }
 	var createAuditGrid = function () {
 		$.ajax({
            url: getController() + "/getMenuInfo?taskCode=",
            // dataType: "application/json;charset=UTF-8",
            type: "get",
            success: function (res) {
            	$.ajax({
		            url: getController() + "/getDivision",
		            // dataType: "application/json;charset=UTF-8",
		            type: "get",
		            success: function (res) {
		            	console.log(res.deptName);
		            	var userProvince = res.deptName;
    	            	var divisionColumns = {		                    
	                        field: userProvince,
	                        title: userProvince,
	                        width: "20%",
	                        align: 'center',
	//                      editor:{type:'numberbox',options:{precision:2}},
	                        formatter: function (value, rowData, rowIndex) {
	
	 							//console.log(rowData.level)
	//							if(rowData.level = 2){
	//								return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionName=${item.divisionName} value=${progressValue}>`
	//							}
	//							if(rowData.level = 0){
	//								return 
	//							}
								if(rowData.level == 1){
		                            let divisionDataList = rowData.divisionDataList
		                            let progressValue 
		                            divisionDataList.forEach(subitem => {
		                            	//debugger;
		                            	if(subitem.divisionName == userProvince){
		                            		progressValue = subitem.progressValue
		                            	}
		                                
		                            })		                        
			                        return progressValue
								}
								if(rowData.level == 2){
									let divisionDataList = rowData.divisionDataList
		                            let progressValue 
		                            let divisionCode
		                            divisionDataList.forEach(subitem => {
		                            	//debugger;
		                            	if(subitem.divisionName == userProvince){
		                            		progressValue = subitem.progressValue
		                            		divisionCode = subitem.divisionCode
		                            	}
		                                
		                            })		             
									return `<input type="number" class="form-control"  onchange="checkNumberValue(this)" data-taskCode = ${rowData.taskCode} data-divisionCode=${divisionCode} value=${progressValue}>`
								}
		                       
		                        //
	                        }
	                    }
                    	$.ajax({
				            url: getController() + "/getMenuInfos",
				            // dataType: "application/json;charset=UTF-8",
				            type: "get",
				            success: function (res) {
				            	var datajson = [];
				            	datajson.push(res);
				            	//console.log(datajson)
		    					$("#auditGrid").treegrid({
						            //url: getController() + "/getMenuInfos",
						            //method:"GET",
						            fitColumns: true,
						            autoRowHeight: false,
						            nowrap: false,
						            idField: 'taskCode',
						            treeField: 'taskName',
									frozenColumns: [[
						                {
						                    field: 'taskName',
						                    title: '任务名称',
						                    width: '50%',
						                    
						                }
							        ]],
						            columns: [
						                [
						                divisionColumns
						                ]
						            ],
						           	data:datajson,
						            // fit: true,
						            onLoadSuccess: function (data) {
						            	$(".tree-icon,.tree-file").removeClass("tree-icon tree-file");
						        		$(".tree-icon,.tree-folder").removeClass("tree-icon tree-folder tree-folder-open tree-folder-closed"); 
						                // console.log(data)
						            },
						            // pagination: true,
						            // pageSize: 10
						        });
				            }
		            	}) 
		            }
		        })        	
            	
            }
        })
 	}
//  var createAuditGrid = function () {
//  	$.ajax({
//          url: getController() + "/getMenuInfo?taskCode=",
//          // dataType: "application/json;charset=UTF-8",
//          type: "get",
//          success: function (res) {
//          	var DataList = res[0].divisionDataList;
//          	console.log(DataList)
//          	$.ajax({
//		            url: getController() + "/getDivision",
//		            // dataType: "application/json;charset=UTF-8",
//		            type: "get",
//		            success: function (res) {
//		            	console.log(res.deptName);
//		            	var userProvince = res.deptName;
////  	            	var columns = DataList.map(item => {
////  	            		if(item.divisionName == userProvince){
////  	            			let obj = {
////			                        field: item.divisionCode,
////			                        title: item.divisionName,
////			                        width: 270,
////			                        align: 'center',
////			//                      editor:{type:'numberbox',options:{precision:2}},
////			                        formatter: function (value, rowData, rowIndex) {
////			//                          let divisionDataList = rowData.divisionDataList
////			//                          let progressValue 
////			//                          divisionDataList.forEach(item => {
////			//                              progressValue = item.progressValue
////			//                          })
////				                        
////				                        return item.progressValue
////				                        //return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionName=${item.divisionName} value=${progressValue}>`
////			                        }
////			                    }
////			                    return obj
////  	            		}
////		                    
////		                })
//  	            	var columns = {    	            		
//	                        field: userProvince,
//	                        title: userProvince,
//	                        width: 270,
//	                        align: 'center',
//	//                      editor:{type:'numberbox',options:{precision:2}},
//	                        formatter: function (value, rowData, rowIndex) {
//	                          	let divisionDataList = rowData.divisionDataList
//	                          	let progressValue 
//                        		divisionDataList.forEach(subitem => {
//	                              	if(subitem.divisionName == userProvince){
//	                            		progressValue = subitem.progressValue
//	                            	}
//	                          	})
//		                        
//		                        return progressValue
//		                        //return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionName=${item.divisionName} value=${progressValue}>`
//	                        }
//			                    
//  	            	}
//		            	console.log(columns)
//		            	var subcolumns = {
//	                        field: userProvince,
//	                        width: 270,
//	                        align: 'center',
//	//                      editor:{type:'numberbox',options:{precision:2}},
//	                        formatter: function (value, rowData, rowIndex) {
//	                      		let divisionDataList = rowData.divisionDataList
//	                          	let progressValue 
//                        		divisionDataList.forEach(subitem => {
//	                              	if(subitem.divisionName == userProvince){
//	                            		progressValue = subitem.progressValue
//	                            	}
//	                          	})
//		                        
//		                        return progressValue
//		                        //return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionCode=${item.divisionCode} value=${progressValue}>`
//	                        }
//	                    }
//		            	console.log(subcolumns)
//		            	var ssubcolumns = {
//	                        field: userProvince,
//	                        width: 270,
//	                        align: 'center',
//	//                      editor : {
//	//                      	type: 'numberbox',
//	//                  	},
//	                        formatter: function (value, rowData, rowIndex) {
//                        		let divisionDataList = rowData.divisionDataList
//	                          	let progressValue
//	                          	let divisionCode
//	                          	divisionDataList.forEach(subitem => {
//	                              	if(subitem.divisionName == userProvince){
//	                            		progressValue = subitem.progressValue
//	                            		divisionCode = subitem.divisionCode
//	                            	}
//	                          	})
//		                        
//		                        // return progressValue
//		                        return `<input class="form-control" onkeyup='keyup(this)' data-taskCode = ${rowData.taskCode} data-divisionCode=${divisionCode} value=${progressValue}>`
//	                        }
//	                    }
//		            	console.log(ssubcolumns)
//  	    			$('#dg').datagrid({
//				            url:getController() + "/getMenuInfo?taskCode=",
//				            method:"GET",
//				            singleSelect: true,
//				            fitColumns:false,
//				            rownumbers: false,
//				            resizable: false,
//				            fixed: true,
//				            nowrap: true,
//				            striped: true, //条纹
//				            width: "100%",
//				            height: "auto",            
//				            showFooter:true,            
//				            columns: [
//				                [
//				                	{
//					                    field: 'taskName',
//					                    title: '任务名称',
//					                    align: 'left',
//					                    width: 420,
//					 
//					                },
//				                	columns
//				                ]
//				            ],
//				            view: detailview,
//							detailFormatter: function(value, rows){
//								return  '<div style="padding:0px"><table class="ddv"></table></div>';		
//							},
//							onExpandRow: function(index,row){
//								var ddv = $(this).datagrid('getRowDetail',index).find('table.ddv');
//								ddv.datagrid({
//									url:getController() + "/getMenuInfo?taskCode="+row.taskCode,
//									method:"GET",
//									showHeader:false,
//									fitColumns:false,
//									singleSelect:true,
//									rownumbers:false,
//									height:'auto',
//									columns:[
//										[{
//						                    field: 'taskName',
//						                    align: 'left',
//						                    width: 392,
//					                	},
//					                	subcolumns
//										]
//									],
//						            view: detailview,
//									detailFormatter: function(value, rows){
//										return  '<div style="padding:0px"><table class="dddv"></table></div>';		
//									},
//									onExpandRow: function(index,row){
//										var dddv = $(this).datagrid('getRowDetail',index).find('table.dddv');
//										dddv.datagrid({
//											url:getController() + "/getMenuInfo?taskCode="+row.taskCode,
//											method:"GET",
//											showHeader:false,
//											fitColumns:false,
//											nowrap: false,
//											singleSelect:true,
//											rownumbers:false,
//											height:'auto',
//											columns:[
//												[{
//								                    field: 'taskName',
//								                    align: 'center',
//								                    width: 389,
//							                	},
//							                	ssubcolumns
//												]
//											],
//											onLoad:function(){
//							                        ddv.datagrid('fixDetailRowHeight',index);
//							                        ddv.datagrid('selectRow',index);
//							                        ddv.datagrid('getRowDetail',index).find('form').form('load',row);
//							                        ddv.datagrid('fixDetailRowHeight',index);
//							                        ddv.datagrid('fixRowHeight', index);  
//							                    },
//											onResize:function(){
//												ddv.datagrid('fixDetailRowHeight',index);
//											},
//											onLoadSuccess:function(){
//												var rows = dddv.datagrid('getRows');
//								                for ( var i = 0; i < rows.length; i++) {
//								                    dddv.datagrid('beginEdit', i);
//								                }
//												setTimeout(function(){
//													ddv.datagrid('fixDetailRowHeight',index);
//													ddv.datagrid('fixRowHeight',index);//防止出现滑动条 
//												},0);
//											}
//										});
//									},
//									onLoad:function(){
//					                        $('#dg').datagrid('fixDetailRowHeight',index);
//					                        $('#dg').datagrid('selectRow',index);
//					                        $('#dg').datagrid('getRowDetail',index).find('form').form('load',row);
//					                        $('#dg').datagrid('fixDetailRowHeight',index);
//					                        $('#dg').datagrid('fixRowHeight', index);  
//					                    },
//									onResize:function(){
//										$('#dg').datagrid('fixDetailRowHeight',index);
//									},
//									onLoadSuccess:function(){
//		//								var rows = ddv.datagrid('getRows');
//		//				                for ( var i = 0; i < rows.length; i++) {
//		//				                    ddv.datagrid('beginEdit', i);
//		//				                }
//										setTimeout(function(){
//											$('#dg').datagrid('fixDetailRowHeight',index);
//											$('#dg').datagrid('fixRowHeight',index);//防止出现滑动条 
//										},0);
//									}
//								});
//							},
//		
//				        });
//		            	
//		            }
//		        })
//          	
//
//
//          }
//      })
//
//	};

    // 初始化按钮 保存
    var btnInit = function () {
        $('#saveBtn').on('click', function () {
        	debugger;
        	var params = [];
        	for(let objkey in obj){
			    //console.log(objkey+"----->"+obj[objkey]);
			    // id----->1
				// name----->apple
				// price----->4
				var newobj = {
					"taskCode": objkey.split("-")[0],
			      	"divisionCode": objkey.split("-")[1],
			      	"progressValue": obj[objkey]
				}
				params.push(newobj)
			}
	 		//console.log(params)
//			var rows = $("#dg").datagrid('getRows');
////          for ( var i = 0; i < rows.length; i++) {
////              $("#dg").datagrid('endEdit', i);
////          }
//
//          var metaColumns = $("#dg").datagrid('getChanges');
////          for ( var i = 0; i < rows.length; i++) {
////              $("#dg").datagrid('beginEdit', i);
////          }
            $.ajax({
                type: "post",
                url: getController()+ '/update',
                contentType: "application/json",
                data: JSON.stringify(params),
                success: function(res){
                    //保存成功后重新获取表信息
                    obj = {};
                    Util.alert(res.message);
                    createAuditGrid();
                    
                }
            });


        })
        
    }
    // 用过菜单ID找菜单名称 @menuId
    var getMenuNameById = function (id) {
        return Menu.filter(item => {
            return item.menuId == id
        })
    }
    // 导出
    var exportProject = function () {
        // 把已选择的行政区划的divisionCode作为参数
        var divisions = selectedDivisions.map(item => {
            return item.divisionCode
        }).toString()
        // 把已选择的菜单类型的menuId 作为参数
        var menuIds = selectedMenus.map(item => {
            return item.menuId
        }).toString()
        var params = {
            startTime: $('#dt1').datebox('getValue'),
            endTime: $('#dt2').datebox('getValue'),
            dataType: $('#dataType').val() || '0',
            divisions,
            menuIds,
            type: $('#type').val(),
        }
        // $.ajax({
        //     url: getController() + "/isEmpty",
        //     data: params,
        //     type: "get",
        //     success: function (data) {
        //         // console.log(data);
        //         if (data.message == '否') {
        //             window.location.href = getController() + "/export?startTime=" + (params.startTime || '') + "&endTime=" + (params.endTime || '') + "&dataType=" + (params.dataType || '') + "&divisions=" + (params.divisions || '') + "&menuIds=" + (params.menuIds || '') + "&type=" + (params.type || '');
        //         } else if (data.message == '是') {
        //             Util.alert('该类型数据数据为空，无法导出！');
        //         } else {
        //             // 未选择类型，请选择一种类型！
        //             Util.alert(data.message);
        //         }
        //     }
        // });
        window.location.href = getController() + "/export?startTime=" + (params.startTime || '') + "&endTime=" + (params.endTime || '') + "&dataType=" + (params.dataType || '') + "&divisions=" + (params.divisions || '') + "&menuIds=" + (params.menuIds || '') + "&type=" + (params.type || '');
    }
    return {
        init:init
    }
})